package com.ahao.service;

import com.ahao.dao.ClazzDao;
import com.ahao.model.Clazz;
import com.ahao.model.ClazzDTO;
import com.ahao.model.RespPageBean;
import com.ahao.utils.CommonsUtils;

import java.sql.SQLException;
import java.util.List;


public class ClazzService {
    ClazzDao clazzDao = new ClazzDao();

    /**
     * 分页查询所有班级
     * @param gid
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    public RespPageBean getClazzByPage(String gid, String page, String rows, String sort, String order) {
        if (page == null || "".equals(page)) {
            //如果没有传递 page，默认 page 为 1
            page = "1";
        }
        if (rows == null || "".equals(rows)) {
            rows = Integer.MAX_VALUE + "";
        }
        if (sort == null || "".equals(sort)) {
            sort = "cid";
        }
        if (order == null || "".equals(order)) {
            order = "asc";
        }
        try {
            //在当前查询条件下，总记录数
            Long total = clazzDao.getTotal(gid);
            int offset = Integer.parseInt(page);
            int size = Integer.parseInt(rows);
            //按照条件进行查询
            List<ClazzDTO> list = clazzDao.getClazzByPage(gid,(offset-1)*size,size,sort,order);
            return new RespPageBean(total,list);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加班级
     * @param clazzName
     * @param gid
     * @return
     */
    public Integer addClazz(String clazzName, String gid) {
        if (clazzName == null || gid == null || clazzName.equals("") || gid.equals("")) {
            return CommonsUtils.ILLEGAL_PARAM;
        }
        Clazz clazz = null;
        try {
            clazz = clazzDao.getClazzByName(clazzName);
            if(clazz != null){
                return CommonsUtils.TABLE_DATA_REPEAT;
            }
            Integer i = clazzDao.addClazz(clazzName, gid);
            return i==1?CommonsUtils.UPDATE_SUCCESS:CommonsUtils.UPDATE_FAIL;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return CommonsUtils.OTHER_EXCEPTION;
    }

    /**
     * 根据班级id删除班级
     * @param cid
     * @return
     */
    public Integer deleteClazz(String cid) {
        if (cid == null || cid.equals("")) {
            return CommonsUtils.ILLEGAL_PARAM;
        }
        try {
            Clazz clazz = clazzDao.getClazzByCid(cid);
            if(clazz == null){
                return CommonsUtils.OTHER_EXCEPTION;
            }
            Integer i = clazzDao.deleteClazz(cid);
            return i==1?CommonsUtils.UPDATE_SUCCESS:CommonsUtils.OTHER_EXCEPTION;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return CommonsUtils.OTHER_EXCEPTION;
    }
}
